import axios from 'axios'
import router from '../router'

const BASE_URL = 'http://localhost:3000'

axios.interceptors.request.use((config) => {
    let jwtToken = window.localStorage.getItem('jwtToken')
    if(jwtToken) {
        // 将token携带在请求头中
        config.headers.Authorization = jwtToken
    }
    return config
})

axios.interceptors.response.use(
    (res) => {
        if (res.data.code !== 0) {
            return Promise.reject(res.data.error)
        } else if (res.data.code === 3) {
            router.push('/login')
        }
        return res
    },
    (err) => {
        if (err.response.status >= 400 && err.response.status < 500) { // 登录过期
            router.push('/login')
        }
        return Promise.reject(err.response.data.error)
    }
)

export function post(url, body) {
    return axios.post(BASE_URL + url, body)
}